package org.example.code;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.example.code.constants.Constants;
import org.example.code.model.CaptchaInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;


@RequestMapping("Captcha")
@RestController
public class CaptchaController {

    private static final long setTime = 60*1000;

    @Autowired
    private CaptchaInfo captchaInfo;


    @RequestMapping("get")
    public void getCaptcha(HttpServletResponse response, HttpSession session) throws IOException {
        //定义图形验证码的长、宽、验证码字符数、干扰线宽度
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(captchaInfo.getWidth(), captchaInfo.getHeight(), captchaInfo.getCodeCount(), captchaInfo.getCircleCount());
        //设置响应类型
        response.setContentType("img/png");
        response.setHeader("Progma","No-cache");
        captcha.write(response.getOutputStream());
        String code = captcha.getCode();
//        存储在Session中，由于判断
/*        放入常量类中
        session.setAttribute(Constants.SESSION_KEY,code);
        session.setAttribute(Constants.SESSION_TIME,new Date());*/

        session.setAttribute(captchaInfo.getSession().getSESSION_KEY(), code);
        session.setAttribute(captchaInfo.getSession().getSESSION_TIME(),new Date());

        //关闭流
        response.getOutputStream().close();

    }

    @RequestMapping("check")
    public String  check(String inCode,HttpSession session){
        if(!StringUtils.hasLength(inCode)){
           return "输入为空";
        }
        String captchaKey = (String) session.getAttribute(Constants.SESSION_KEY);
        Date captchaTime = (Date) session.getAttribute(Constants.SESSION_TIME);
        long nowTime = System.currentTimeMillis();

        if(captchaKey.equalsIgnoreCase(inCode)){
            if((captchaTime.getTime() != 0) && ((nowTime - captchaTime.getTime()) < setTime)){
                return "验证码正确";
            }
        }
        return "验证码有误";
    }

}
